//
//  Array+AG.swift
//  AG
//
//  Created by zhuxuhong on 2020/10/23.
//  Copyright © 2020 AgoCulture. All rights reserved.
//


public extension Array where Element: Equatable {
    func befores(of current: Element) -> [Element] {
        guard let idx = firstIndex(where: { $0 == current }) else {
            return []
        }
        return befores(at: idx)
    }
    
    func befores(at index: Int) -> [Element] {
        guard index < count else {
            return []
        }
        return Array(prefix(upTo: index))
    }
    
    func afters(of current: Element) -> [Element] {
        guard let idx = firstIndex(where: { $0 == current }) else {
            return []
        }
        return afters(at: idx)
    }
    
    func afters(at index: Int) -> [Element] {
        guard index+1 < count else {
            return []
        }
        return Array(suffix(from: index+1))
    }
}

extension Array where Element: Equatable {
    public func previous(of current: Element) -> Element? {
        guard let idx = firstIndex(where: { $0 == current }) else {
            return nil
        }
        return previous(at: idx)
    }
    public func next(of current: Element) -> Element? {
        guard let idx = firstIndex(where: { $0 == current }) else {
            return nil
        }
        return next(at: idx)
    }
    
    public func previous(at index: Int) -> Element? {
        if index >= 1, index < count {
            return self[index - 1]
        }
        return nil
    }
    public func next(at index: Int) -> Element? {
        if index >= -1, index < count-1 {
            return self[index + 1]
        }
        return nil
    }
}


extension ArraySlice where Element: Any {
    public var bw_toArray: [Element] {
        return Array(self)
    }
}

extension Array where Element: Any {
    public func bw_matches(where condition: @escaping (Element)->Bool) -> Self {
        return compactMap{
            if condition($0) {
                return $0
            }
            return nil
        }
    }
}

extension Array where Element: Hashable {
    public func bw_toSet() -> Set<Element> {
        return Set<Element>(self)
    }
}

extension Array where Element: NSObject{
    public mutating func bw_remove(object: Element){
        removeAll {
            $0 == object
        }
    }
}
